<template>
  <div>
    <van-form @submit="onSubmit">
      <van-field v-model="username" name="username" placeholder="用户名" :rules="[{ required: true, message: '请填写用户名' }]"
        style="width: 100%; height: 40px; font-size: 16px;padding-top: 10px;" />
      <van-field v-model="password" type="password" name="password" placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
        style="width: 100%; height: 40px; font-size: 16px;padding-top: 10px;" />
      <van-field v-model="digit" clearable placeholder="验证码" name="captcha_code"
        style="width: 100%; height: 40px; font-size: 16px;padding-top: 10px;">
        <template #button>
          <img :src="code"
            style="height: 30px;width: 70px;margin-right: 5px;position: absolute; top: -5px;right: 55px;">
          <van-button type="primary"
            style="width: 60px;height: 30px; font-size: 10px; background-color: white;color: black;position: absolute; top: -5px;right: 0;border: 0;">
            看不清 换一张</van-button>
        </template>
      </van-field>
      <p style="color: red;">温馨提示: 未注册过的账号, 登录时将自动注册</p>
      <p style="color: red;">注册过的用户可凭账号密码登录</p>
      <div style="margin: 16px;">
        <van-button block type="info" native-type="submit"
          style="width: 100%; height: 40px;border-radius: 5px; background-color: rgb(76,217,100); border: 0;">
          登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        username: '',
        password: '',
        digit: '',
        status: [],
        captcha_code: '',
        code: [],
        user: [],
      };
    },
    created() {
      this.$store.commit("changeTitle", "密码登录");
      //请求验证码 https://elm.cangdu.org/v1/captchas
      const req1 = this.axios.post(this.$url + "/v1/captchas")
      this.axios.all([req1]).then(this.axios.spread((res1) => {
        this.status = res1.data.status;
        this.code = res1.data.code;
        console.log(this.status);
        console.log(this.code);
      })).catch(err => console.log(err));
    },
    methods: {
      onSubmit(values) {
        console.log('submit', values);
        this.axios.post(this.$url + "/v2/login", values);

        //获取用户信息
        //https://elm.cangdu.org/v1/user
        const req1 = this.axios.get(this.$url + "/v1/user")
        this.axios.all([req1]).then(this.axios.spread((res1) => {
          this.user = res1.data;
          console.log(this.user);
          //将用户信息暂时存入localStroage
          sessionStorage.setItem('user', JSON.stringify(this.user));
          this.$router.push('/my');
        })).catch(err => console.log(err));
      },
    },
  };
</script>

<style lang="less" scoped>
  .van-form {
    margin-top: 20px;
  }
</style>